# -*- coding: utf-8 -*-
#作者：淘小白 vx:TXB2196 官网：i-uni.cn
import openai
import os
import requests
import re
import time
from retrying import retry
from pathlib import Path
import threading
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor, as_completed,ProcessPoolExecutor
import random

'''
脚本依赖库，需要安装的第三方库指令：
pip install openai
pip install retrying

'''

lock_object = threading.RLock()

def get_openai(question,apikey):
try:
os.system('')
openai.api_key = apikey
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
n=1,
max_tokens = 3096,
messages=[
{"role": "system", "content": "你是一个游戏百科达人"},
{"role": "user", "content": question}

]
)
# print(str(response))
return response['choices'][0]['message']['content']
except Exception as e:
return str(e)


@retry(stop_max_attempt_number=2)
def get_answer(key,API_KEYS_PATH,zl_path,zc_keywords,file_path):

zl_title_content = cl_key(key,zl_path)
if zl_title_content:
while True:
apikey = cs_apikey(API_KEYS_PATH)
# print(apikey)
if apikey:
print('----正在根据关键词【  '+key+'  】生成文章，请等待...'+'\n')
new_title = get_openai(zl_title_content[0],apikey)
t_f = get_T(new_title,apikey,API_KEYS_PATH)
if t_f:
print('----OPENAI接口网络已通过'+'\n')
new_zl_title_content = cl_key(key,zl_path)
print('----获取到的新title是'+new_zl_title_content+'\n')
new_content = get_openai(new_zl_title_content[1],apikey)
print('----获取到的新content是'+new_content+'\n')
t_f2 = get_T(new_content,apikey,API_KEYS_PATH)
if t_f2:
if '502' not in new_content and 'Error' not in new_content:
del_keywords(key,file_path,zc_keywords)
return new_title,new_content
else:
pass
else:
pass
else:
pass
else:
print('----APIKEY已全部用完')
return '----APIKEY已全部用完'

# @retry(stop_max_delay=10000) #毫秒级别
def outer(keyword,out_path):
def save_data(response):
try:
fu_key = ['overloaded','Request timed out','Rate limit reached','That model is currently overloaded with other requests']
title, content = response.result()
# result_title = keyword+'('+title+')'
result_title = keyword
if any(keyword in str(content) for keyword in fu_key):
pass
else:
result_content = qx_content(content)
if len(result_content)>200:
with open(out_path+result_title.replace('?','').replace('/','').replace('|','').replace('\\','').replace('"','').replace('>','').replace('<','').replace('*','').replace(' ','').replace('^','')+'.txt','w+' ,encoding='utf8') as w:
print('----'+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
print('++++正在保存文章：'+result_title)
w.write(result_title+'******'+result_content)
else:
pass
except:
pass
return save_data

#清洗处理生成好的文章
def qx_content(content):
result_content = []
content_lst = re.split('\n',content)
n = 0
for i in content_lst:
if len(i)>1:
if '<h' not in i and '</h' not in i and '<p' not in i and '</p' not in i and 'title' not in i:
result_content.append('<p>'+i+'</p>')
else:
result_content.append(i)
n+=1
else:
pass

content = ''.join(result_content)
return ''.join(content)

def cl_key(key,zl_path):
zl_content =[]
zl_title = []
with open(zl_path,'r',encoding='utf8') as zl_f:
zl_contents = zl_f.readlines()
n = 0
for z in zl_contents:
if n ==0:
if "<keyword>" not in z:
  z = z.replace('\n','')
  zl_title.append(z)
  else:
  z = z.replace(r'<keyword>',key).replace('\n','')
    zl_title.append(z)
    else:
    if "<newtitle>" not in z:
      z = z.replace('\n','')
      zl_content.append(z)
      else:
      z = z.replace(r'<newtitle>',key).replace('\n','')
        zl_content.append(z)
        n+=1

        return ''.join(zl_title),''.join(zl_content)

        def cs_apikey(API_KEYS_PATH):
        zc_apikeys = []
        with open(API_KEYS_PATH,'r',encoding='utf8') as k_f:
        A_keys = k_f.readlines()
        for i in A_keys:
        i = i.replace('\n','').replace('\ufeff','').replace('<0xfeff>','')
        if len(i)>0:
        zc_apikeys.append(i)
        else:
        pass
        result_apikey = random.choice(zc_apikeys)
        return result_apikey

        def del_apikey(apikey,API_KEYS_PATH):
        zc_apikeys = []
        with open(API_KEYS_PATH,'r',encoding='utf8') as k_f:
        A_keys = k_f.readlines()
        for i in A_keys:
        i = i.replace('\n','').replace('\ufeff','').replace('<0xfeff>','')
        if len(i)>0:
        zc_apikeys.append(i)
        else:
        pass

        with open('用完或者被封账号.txt','a+',encoding='utf8') as cw_f:
        cw_f.write(apikey+'\n')

        zc_apikeys.remove(apikey)

        with open(API_KEYS_PATH,'w',encoding='utf8') as qk_f:
        qk_f.write('')

        with open(API_KEYS_PATH,'a',encoding='utf8') as cx_f:
        for k in zc_apikeys:
        with open(API_KEYS_PATH,'r',encoding='utf8') as tj_f:
        txt_apikeys = tj_f.readlines()
        if k not in ''.join(txt_apikeys):
        cx_f.write(k+'\n')
        else:
        pass

        def del_keywords(key,file_path,zc_keywords):
        zc_keywords.remove(key)
        with open(file_path,'w',encoding='utf8') as qk_f:
        qk_f.write('')
        with open(file_path,'a',encoding='utf8') as cx_f:
        for k in zc_keywords:
        cx_f.write(k+'\n')


        def get_T(e,apikey,API_KEYS_PATH):
        if "host='api.gptmf.top', port=443" in e:
        print('----被墙了，请换用US线路，等待3s后，程序将继续自动执行！')
        time.sleep(3)
        return True
        elif "module 'openai' has no attribute 'ChatCompletion'" in e:
        print('----python第三方库openai库安装错误，win+r--cmd--复制--pip install openai==v0.27.0--粘贴回车--升级库')
        return True
        elif '远程主机强迫关闭' in e:
        print('----官方宕机或者梯子不稳定，等待3s后，程序将继续自动执行！')
        time.sleep(3)
        return True
        elif 'You can retry your request' in e:
        print('----官方宕机或者梯子不稳定，等待3s后，程序将继续自动执行！')
        time.sleep(3)
        return True
        elif '502 Bad Gateway' in e:
        print('----http状态码502，等待30s后，程序将继续自动执行！')
        time.sleep(3)
        return True
        elif 'Rate limit reached' in e:
        print('----官方API接口限速请求预警！等待3秒，程序将继续自动执行！')
        time.sleep(3)
        return True
        elif 'Error communicating with OpenAI' in e:
        print('----连接官网错误，等待3秒，程序将继续自动执行！')
        return True
        elif  'Error' in e:
        print('----请求官网，存在未知错误，延迟3秒请求，程序将继续自动执行！')
        time.sleep(3)
        return True
        elif  'That model is currently overloaded with other requests' in e:
        print('----官网拥挤，延迟3秒请求，程序将继续自动执行！')
        time.sleep(3)
        return True
        elif 'Your access was terminated' in e:
        print('----账号被封or量已用完，正在切换账号')
        del_apikey(apikey,API_KEYS_PATH)
        return False
        elif 'This key is associated with a deactivated account' in e:
        print('----账号被封or量已用完，正在切换账号')
        del_apikey(apikey,API_KEYS_PATH)
        return False
        elif 'You exceeded your current quota' in e:
        print('----账号被封or量已用完，正在切换账号')
        del_apikey(apikey,API_KEYS_PATH)
        return False
        elif 'lncorrect API key' in e:
        print('----apikey格式错误！')
        del_apikey(apikey,API_KEYS_PATH)
        return False
        else:
        return True

        if __name__ == '__main__':

        #这里是数据保存路径
        out_path = 'D:/BaiduNetdiskDownload/黑帽SEO全套源码课程/软件工具程序/权重站所需要的软件/ChatPGPT/ChatPGPT/NEW_chatgpt_8.1.4(2)/NEW_chatgpt_8.1.4/指令版 -8.2.4最新/data/'

        #这里是关键词文件路径，一行一个，编码utf8
        file_path = 'D:/zuixinguanjianci.txt'

        # 这里存放自己的apikey
        API_KEYS_PATH = 'D:/BaiduNetdiskDownload/黑帽SEO全套源码课程/软件工具程序/权重站所需要的软件/ChatPGPT/ChatPGPT/NEW_chatgpt_8.1.4(2)/NEW_chatgpt_8.1.4/指令版 -8.2.4最新/apikey.txt'
        # API_KEYS_PATH = 'D:/BaiduNetdiskDownload/黑帽SEO全套源码课程/软件工具程序/权重站所需要的软件/ChatPGPT/ChatPGPT/NEW_chatgpt_8.1.4(2)/NEW_chatgpt_8.1.4/指令版 -8.2.4最新/apikey.txt'
        # API_KEYS_PATH = 'D:/BaiduNetdiskDownload/黑帽SEO全套源码课程/软件工具程序/权重站所需要的软件/ChatPGPT/ChatPGPT/NEW_chatgpt_8.1.4(2)/NEW_chatgpt_8.1.4/指令版 -8.2.4最新/4apikey.txt'
        #生成指令存放文件路径
        # zl_path = 'D:/BaiduNetdiskDownload/黑帽SEO全套源码课程/软件工具程序/权重站所需要的软件/ChatPGPT/ChatPGPT/NEW_chatgpt_8.1.4(2)/NEW_chatgpt_8.1.4/指令版 -8.2.4最新/超级复杂指令.txt'
        zl_path = 'D:/BaiduNetdiskDownload/黑帽SEO全套源码课程/软件工具程序/权重站所需要的软件/ChatPGPT/ChatPGPT/NEW_chatgpt_8.1.4(2)/NEW_chatgpt_8.1.4/指令版 -8.2.4最新/指令示例1.txt'
        # zl_path = 'D:/BaiduNetdiskDownload/黑帽SEO全套源码课程/软件工具程序/权重站所需要的软件/ChatPGPT/ChatPGPT/NEW_chatgpt_8.1.4(2)/NEW_chatgpt_8.1.4/指令版 -8.2.4最新/指令示例2.txt'


        #0代表单标题，使用chatgpt生成的标题保存
        #1代表双标题，使用关键词+chatgpt生成的标题组合
        #2代表关键词标题，使用关键词作为标题

        title_doubletitle = 1

        #标题链接符
        title_ljf_f = '('
        title_ljf_b = ')'


        pool = ThreadPoolExecutor(100)
        zc_keywords = []
        sa_keywords = []
        with open(file_path,'r',encoding='utf8') as f:
        key_words = f.readlines()
        for i in key_words:
        i = i.replace('\n','').replace('\ufeff','').replace('<0xfeff>','')
        if len(i)>0:
        zc_keywords.append(i)
        sa_keywords.append(i)
        else:
        pass
        for i in zc_keywords:
        fur = pool.submit(get_answer,i,API_KEYS_PATH,zl_path,zc_keywords,file_path)
        fur.add_done_callback(outer(i,out_path))